#pragma once
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/resource.h>

#include "../comm/log.hpp"
#include "../comm/util.hpp"

namespace ns_runner
{
    using namespace ns_util;
    using namespace ns_log;
    class Runner
    {
    public:
        // 设置进程占用资源上限
        static void SetProcSource(int _limit_cpu, int _limit_mem) // 内存:KB
        {
            struct rlimit limit_cpu;
            limit_cpu.rlim_cur = _limit_cpu;
            limit_cpu.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_CPU, &limit_cpu); // SIGXCPU 24

            struct rlimit limit_mem;
            limit_mem.rlim_cur = _limit_mem * 1024;
            limit_mem.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_AS, &limit_mem); // SIGABRT 6
        }

        static int Run(const std::string &file_name, int limit_cpu, int limit_mem)
        {
            std::string _excute = PathUtil::Exe(file_name);
            int _stdin_fd = open(PathUtil::Stdin(file_name).c_str(), O_CREAT | O_RDONLY, 0644);
            int _stdout_fd = open(PathUtil::Stdout(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
            int _stderr_fd = open(PathUtil::StdErr(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                LOG(Loglevel::ERROR) << "运行时打开文件失败\n";
                return -1;
            }

            pid_t pid = fork();
            if (pid < 0)
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                LOG(Loglevel::ERROR) << "运行时创建子进程失败\n";
                return -2;
            }
            else if (pid == 0)
            {
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);
                SetProcSource(limit_cpu, limit_mem);
                execl(_excute.c_str(), _excute.c_str(), nullptr);
                LOG(Loglevel::ERROR) << "运行时程序替换失败\n";
                exit(1);
            }
            else
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                int status = 0;
                waitpid(pid, &status, 0);
                LOG(Loglevel::INFO) << "运行完毕, info: " << (status & 0x7F) << "\n";
                return (status & 0x7F);
            }
        }
    };
}